package com.lfy.service.impl;

import com.lfy.dao.AccountInfoDao;
import com.lfy.dao.Bank2Client;
import com.lfy.service.AccountInfoService;
import io.seata.core.context.RootContext;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Slf4j
public class AccountInfoServiceImpl implements AccountInfoService {

    @Autowired
    AccountInfoDao accountInfoDao;

    @Autowired
    Bank2Client bank2Client;

    @Transactional
    //将`@GlobalTransactional`注解标注在全局事务发起的Service实现方法上，开启全局事务：
    //GlobalTransactionalInterceptor会拦截@GlobalTransactional注解的方法，
    //生成`全局事务ID(XID)`，XID会在整个分布式事务中传递。
    @GlobalTransactional//开启全局事务
    @Override
    public void updateAccountBalance(String accountNo, Double amount) {
        log.info("bank1 service begin,XID:{}", RootContext.getXID());
        //扣减张三的金额
        accountInfoDao.updateAccountBalance(accountNo, amount * -1);
        //远程增加李四的金额
        String transfer = bank2Client.transfer(amount);
        if ("fallback".equals(transfer)) {
            throw new RuntimeException("调用李四微服务异常");
        }
        if (amount == 2) {
            throw new RuntimeException("bank1人为抛出异常");
        }
    }
}